"""
@File: schedule.py
@Project: 约个球
@Author: zhangjian
@Time: 2022.8.22 22:07
@Description: None
"""
import datetime
from model import db

# 多对多的关系
subscriber = db.Table("subscriber",
                      db.Column("schedule_id", db.ForeignKey('schedule.id')),
                      db.Column("user_id",db.ForeignKey("user.id"))
                      )


class ScheduleManager(db.Model):
    __tablename__ = "schedule"
    # 创建主键约束
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # user_id字段 同 user表的id字段建立外键约束关系，对于数据库来说，外键非常影响性能，一般数据库不会创建外键
    user_id = db.Column(db.ForeignKey("user.id"))
    address = db.Column(db.String(256), nullable=False)
    time = db.Column(db.DateTime, nullable=False)
    introduction = db.Column(db.String(512), nullable=False)
    location_x = db.Column(db.Float, nullable=False)
    location_y = db.Column(db.Float, nullable=False)
    CreateAt = db.Column(db.DateTime, default=datetime.datetime.now())
    users = db.relationship("UserManager", secondary=subscriber, backref="invitations")

    def keys(self):
        return ('user_id', 'address', 'introduction', 'location_x', 'location_y')

    def __getitem__(self, item):
        return getattr(self, item)

    def to_json(self):
        return {
            "user_id": self.user_id,
            "address": self.address,
            "introduction": self.introduction
        }

    @classmethod
    def create_invitation(cls, address, time, introduction, location_x, location_y):
        invitation = cls()
        invitation.address = address
        invitation.time = time
        invitation.introduction = introduction
        invitation.location_x = location_x
        invitation.location_y = location_y
        db.session.add(invitation)
        db.session.commit()